package com.example.play

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.children
import com.example.play.model.CardMatchingGame
import java.util.Locale

class CardGame : AppCompatActivity(), View.OnClickListener {

    private lateinit var game: CardMatchingGame
    private val cardButtons = mutableListOf<Button>()
    private lateinit var scoreText: TextView
    private lateinit var resetButton: Button

    companion object {
        const val REQUEST_MAIN_EDIT = 1001
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_card_game)

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.gridLayout)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        val gridLayout = findViewById<android.widget.GridLayout>(R.id.gridLayout)
        scoreText = findViewById(R.id.score)
        resetButton = findViewById(R.id.reset)

        for (v in gridLayout.children) {
            if (v is Button && v.id != R.id.reset) {
                v.setOnClickListener(this)
                cardButtons.add(v)
            }
        }

        game = CardMatchingGame(cardButtons.count())
        updateUI()

        resetButton.setOnClickListener {
            game = CardMatchingGame(cardButtons.count())
            updateUI()
        }

        setupButtonListeners()
    }

    private fun updateUI() {
        for (button in cardButtons) {
            val index = cardButtons.indexOf(button)
            val card = game.cardAtIndex(index)
            button.isEnabled = !card.isMatched
            if (card.isChosen) {
                button.text = card.toString()
                button.setBackgroundColor(Color.WHITE)
            } else {
                button.text = ""
                button.setBackgroundResource(R.drawable.grd)
            }
        }

        scoreText.text = String.format(Locale.getDefault(), "%s %d", "Score:", game.score)
    }

    override fun onClick(v: View?) {
        if (v is Button && v.id != R.id.reset) {
            val index = cardButtons.indexOf(v)
            game.chooseCardAtIndex(index)
            updateUI()
        }
    }

    private fun setupButtonListeners() {
        findViewById<Button>(R.id.back).setOnClickListener {
            val intent = Intent(this, MainActivity::class.java)
            startActivityForResult(intent, REQUEST_MAIN_EDIT)
        }
    }
}